package com.heaven1949.tmall.common.core.dto;

import lombok.Data;

import java.io.Serializable;

/**
 * 通用返回对象
 *
 * @author zhangjian
 * @date 2023-03-09 13:39:22
 */
@Data
public class ApiResult<T> implements Serializable {

    /**
     * 响应状态码
     */
    private String code;
    /**
     * 响应描述信息
     */
    private String msg;
    /**
     * 响应内容
     */
    private T data;

    public static <T> ApiResult<T> success() {
        return success(null);
    }

    public static <T> ApiResult<T> success(T data) {
        ApiResult<T> result = new ApiResult<>();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(data);
        return result;
    }

    public static <T> ApiResult<T> failed() {
        return result(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), ResultCode.SYSTEM_EXECUTION_ERROR.getMsg(), null);
    }

    public static <T> ApiResult<T> failed(String msg) {
        return result(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), msg, null);
    }

    public static <T> ApiResult<T> judge(boolean status) {
        if (status) {
            return success();
        } else {
            return failed();
        }
    }

    public static <T> ApiResult<T> failed(IResultCode resultCode) {
        return result(resultCode.getCode(), resultCode.getMsg(), null);
    }

    public static <T> ApiResult<T> failed(IResultCode resultCode, String msg) {
        return result(resultCode.getCode(), msg, null);
    }

    public static <T> ApiResult<T> failed(IResultCode resultCode, T data) {
        return result(resultCode.getCode(), resultCode.getMsg(), data);
    }

    private static <T> ApiResult<T> result(IResultCode resultCode, T data) {
        return result(resultCode.getCode(), resultCode.getMsg(), data);
    }

    private static <T> ApiResult<T> result(String code, String msg, T data) {
        ApiResult<T> result = new ApiResult<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }

    public static boolean isSuccess(ApiResult<?> result) {
        return result != null && ResultCode.SUCCESS.getCode().equals(result.getCode());
    }

}